<script setup lang='ts'>
import { computed, ref ,h} from 'vue'
import { NDropdown,NTooltip, useMessage,NButton } from 'naive-ui'
import AvatarComponent from './Avatar.vue'
import TextComponent from './Text.vue'
import { SvgIcon } from '@/components/common'
import { useIconRender } from '@/hooks/useIconRender'
import { t } from '@/locales'
import { useBasicLayout } from '@/hooks/useBasicLayout'
import { copyToClip } from '@/utils/copy'
import { useRoute } from 'vue-router'
import { useChatStore, usePromptStore } from '@/store'
import { downloadFile } from '@/api'
interface Props {
  dateTime?: string
  text?: string
  inversion?: boolean
  error?: boolean
  loading?: boolean
  item?:any
  conversationOptions?:any
  last:boolean
}

interface Emit {
  (ev: 'regenerate'): void
  (ev: 'delete'): void
  (ev: 'updateContent',type:number): void
  (ev: 'onUpdateEdit',isEdit:boolean): void
  (ev: 'fleshReport',type:number): void
  
}

const route = useRoute()
const { uuid } = route.params as { uuid: string }
const chatStore = useChatStore()

const props = defineProps<Props>()

const emit = defineEmits<Emit>()

const { isMobile } = useBasicLayout()

const { iconRender } = useIconRender()

const message = useMessage()

const textRef = ref<any>()

const asRawText = ref(props.inversion)
const conversationOptions = computed(()=>props.conversationOptions)
const last = computed(()=>props.last)
const dataSources = computed(() => chatStore.getChatByUuid(uuid))
const isEditDisable = computed(()=>dataSources.value.findIndex(data=>data.isEdit)!=-1)
const messageRef = ref<HTMLElement>()
const isEdit = ref<boolean>(false)
const options = computed(() => {
  let common = [

    {
      label: t('chat.copy'),
      key: 'copyText',
      icon: iconRender({ icon: 'ri:file-copy-2-line' }),
      type:'',
    },
    {
      label: t('common.delete'),
      key: 'delete',
      type:'error',
      icon: iconRender({ icon: 'ri:delete-bin-line' }),
    },
    {
      label: '下载word',
      key: 'downWord',
      type:'primary',
      icon: () => h('img', { src: new URL('@/assets/word.png', import.meta.url),class:'w-3 word-icon' }),
    },
    {
      label: '下载pdf',
      key: 'downPdf',
      type:'primary',
      icon: () => h('img', { src: new URL('@/assets/pdf.png', import.meta.url),class:'w-3 word-icon' }),
    },
  ]

  //显示原文按钮
  // if (!props.inversion) {
  //   common.unshift({
  //     label: asRawText.value ? t('chat.preview') : t('chat.showRawText'),
  //     key: 'toggleRenderType',
  //     icon: iconRender({ icon: asRawText.value ? 'ic:outline-code-off' : 'ic:outline-code' }),
  //   })
  // }
  if(conversationOptions.value?.isReportContent){
      common = [
            {
              label: '优化报告',
              key: 'fleshReport',
              type:'',
              icon: iconRender({ icon: 'lucide:edit' }),
            },
        ...common
      ]
    if(!props.item.isEdit){

      common = [
            {
              label: '编辑报告',
              key: 'editReport',
              type:'',
              icon: iconRender({ icon: 'lucide:edit' }),
            },
        ...common
      ]
    }else{
        common = [
            {
              label:'保存报告',
              key: 'saveReport',
            type:'primary',
              icon: iconRender({ icon: 'lucide:edit' }),
            },
        ...common
      ]
    }
  }else{
    if(props.last){//必须在最后的大纲才可以进行编辑生成报告操作

      if(!props.item.isEdit){

        common = [
              {
                label: '编辑大纲',
                key: 'editOutline',
                
                type:'',
                icon: iconRender({ icon: 'lucide:edit' }),
              },
              {
                label:'继续生成报告',
                key: 'getReport',
              type:'primary',
                icon: iconRender({ icon: 'lucide:edit' }),
              },
          ...common
        ]
      }else{
          common = [
              {
                label:'保存大纲',
                key: 'saveOutline',
                type:'primary',
                icon: iconRender({ icon: 'lucide:edit' }),
              },
          ...common
        ]
      }
    }
  }
  return common
})

function handleSelect(key: 'copyText' | 'delete' | 'toggleRenderType'|'downWord'|'downPdf'|'editOutline'|'saveOutline'|'editReport'|'saveReport'|'getReport'|'fleshReport') {
  

  switch (key) {
    case 'copyText':
      handleCopy()
      return
    case 'fleshReport':
      fleshReport()
      return
    case 'editOutline':
      handleEdit(0)
      return
    case 'saveOutline':
      handleEdit(1)
      return
    case 'getReport':
      getReport(1)
      return
    case 'editReport':
      handleReportEdit(0)
      return
    case 'saveReport':
      handleReportEdit(1)
      return
    case 'toggleRenderType':
      asRawText.value = !asRawText.value
      return
    case 'delete':
      emit('delete')
      return
    case 'downWord':
        window.location.href = `http://192.168.2.29:18020/ai-report/dialog/content/download?operationType=1&dialogContentBlockId=${props.item.conversationOptions.contentBlockId}&fileType=1`

      return
    case 'downPdf':
      
       window.location.href = `http://192.168.2.29:18020/ai-report/dialog/content/download?operationType=1&dialogContentBlockId=${props.item.conversationOptions.contentBlockId}&fileType=2`
      return
  }
}

function getReport(type:number){
      emit('updateContent',0)
}
function fleshReport(){
      emit('fleshReport',4)

}
function handleRegenerate() {
  messageRef.value?.scrollIntoView()
  emit('regenerate')
}
function handleReportEdit(type:number){
   if(type==0){
    isEdit.value = true;
    emit('onUpdateEdit',true)
    textRef.value?.editorMdChange()
  }else{
    isEdit.value = false;
    emit('onUpdateEdit',false)
    textRef.value?.saveMdChange()
      emit('updateContent',1)
  }
}

async function handleEdit(type:number){
  if(type==0){

    isEdit.value = true;
    emit('onUpdateEdit',true)
    textRef.value?.editorMdChange()
  }else{
    
    textRef.value?.saveMdChange()
    isEdit.value = false;
    emit('onUpdateEdit',false)
      emit('updateContent',1)

  }
}
async function handleCopy() {
  try {
    await copyToClip(props.text || '')
    message.success(t('chat.copied'))
  }
  catch {
    message.error(t('chat.copyFailed'))
  }
}
</script>

<template>
  <div
    ref="messageRef"
    class="flex w-full mb-6 overflow-hidden"
    :class="[{ 'flex-row-reverse': inversion }]"
  >
    <div
      class="flex items-center justify-center flex-shrink-0 h-8 overflow-hidden rounded-full basis-8"
      :class="[inversion ? 'ml-2' : 'mr-2']"
    >
      <AvatarComponent :image="inversion" />
    </div>
    <div class="overflow-hidden text-sm " :class="[inversion ? 'items-end' : 'items-start']">
      <p class="text-xs text-[#b4bbc4]" :class="[inversion ? 'text-right' : 'text-left']">
        {{ dateTime }}
      </p>
      <div
        class="flex items-end gap-1 mt-2"
        :class="[inversion ? 'flex-row-reverse' : 'flex-row']"
      >
        <TextComponent
          ref="textRef"
          :inversion="inversion"
          :error="error"
          :text="text"
          :loading="loading"
          :last="last"
          :as-raw-text="asRawText"
        />
        <div class="flex flex-col">
          <div class="flex flex-col  gap-1 mt-2 " v-if="!inversion" >
             <NButton :type="item.type" v-for="(item,index) in options" :disabled="loading||(item.label.includes('编辑')&&isEditDisable)" :key="index" @click="handleSelect(item.key)">
              {{item.label}}</NButton>
             <NButton    @click="handleRegenerate">再来一次</NButton>
          </div>

          <!-- <NDropdown
            :trigger="'hover'"
            v-if="!inversion"
            :placement="!inversion ? 'right' : 'left'"
            :options="options"
            @select="handleSelect"
          >
            <button class="transition text-neutral-300 hover:text-neutral-800 dark:hover:text-neutral-200">
              <SvgIcon icon="ri:more-2-fill" />
            </button>
          </NDropdown> -->
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less">
// .icon
</style>
